import Lpars,Lsql,Lsmtp, Llogging
import time
import sys
import logging

log=logging.getLogger('bishop')

def site_constr(site):
    try:
        log.debug(' Starting %s....' % site)
        noedit_content=[]
        edited_db=[]
        content=[]
        newstext=''
        if site =='kinonews.ru':
            mod_id=Lpars.kinonews_id
            mod_text=Lpars.kinonews_text
        elif site =='bash.il':
            mod_id=Lpars.bash_id
            mod_text=Lpars.bash_text
        elif site =='ixbt.com':
            mod_id=Lpars.ixbt_com
            mod_text=Lpars.ixbt_text
        elif site =='kanobu.ru':
            mod_id=Lpars.kanobu_ru
            mod_text=Lpars.kanobu_text
        elif site =='Goha.ru':
            mod_id=Lpars.GoHa_ru
            mod_text=Lpars.GoHa_text
        elif site =='Habrahabr.ru':
            mod_id=Lpars.Habrahabr_ru
            mod_text=Lpars.habratext
        else:
            sys.exit(0)
        for i in mod_id():
            noedit_content.append(i)    
        log.debug(' List from %s ready' % site)
        list_news_from_db=Lsql.select_db(site,'news')
        for i in  list_news_from_db:
            edited_db.append(i[0])
        log.debug(' List from bishop_db ready')
        for i in noedit_content:
            if i in edited_db:pass
            else:content.append(i)
        log.debug(' News from site>>> News from bishop_db')
        if len(content)>0:
            log.debug(' News to add is %s' % len(content))
            for k in content:
                newstext+=mod_text(k)
            newscontent=list(newstext.split('?/|/?'))[0:-1]
            log.debug(' News_text ready')
            for i in content:
                Lsql.insert_db(site,i,newscontent[0].replace('\'',''))
                newscontent=newscontent[1:]
            log.debug(' Insert data in db - ready\n')
        else:
            log.debug(' Error!! New news is 0\n')
    except:
        log.exception("exception message")

def sendingmail():
    id_from_db=[]
    text_from_db=[]
    edited_message=''
    log.debug(' Selected data from db')
    content_list=Lsql.select_db()
    for i in content_list:
        id_from_db.append(i[0])
        text_from_db.append(i[1])
    for i in text_from_db:
       edited_message+=i+'\n--------------------------------------------------------------------------------------\n'
    log.debug(' Sending email....')   
    if len(id_from_db)>0:
        try:
            Lsmtp.Sender_text_yandex(edited_message,subject='Bishop email from_YANDEX',
                                     toad='bishop.py@yandex.ru')
            log.debug(' \t\tEmail was sended')
        except:
            log.exception("exception message")
            Lsmtp.Sender_text_mailRu(edited_message,subject='Bishop email from_Mail.ru',
                                     toad='bishop.py@yandex.ru')                                      
            log.debug(' \t\tEmail was sended')    
        log.debug(' Update data in db start') 
        for i in id_from_db:
            Lsql.update_db(i)
            log.debug('\tupadating id-%s' % i)
        log.debug(' Update data in db end')
    else:log.debug(' \t\tNo data to send\n')

def logsender():
        c=open('C:\Python32\logrus\Bishop\logs\Bishop.log')
        k=c.read()
        readed_log=k.split('\n------------------\n')[-2]
        c.close()
        try:
            Lsmtp.Sender_text_yandex(readed_log,subject='Bishop Bishop_log_yd.ru',
                                 toad='logrus_ak@ukr.net')
        except:
            Lsmtp.Sender_text_mailRu(readed_log,subject='Bishop Bishop_log_m.ru'
                                 ,toad='logrus_ak@ukr.net')

def main():
    while True:
        b=input('Введите команду:\n1 - Запуск скрипта\n2 - Выход\n\t')
        if b =='1':
            try:
                x=int(input('Введите время ожидания скрипта перед перезапуском (часы)\n\t'))
                main_timer(x)
            except ValueError:
                print('\n\t!!!Ошибка - Нужно указать целое число!!!\n')
                main()
        elif b =='2':
            sys.exit(0)
        else: print('Неверная команда\n--------------------------------\n\n')

def main_timer(x):
    while True:
            try:
                try:
                    site_constr('Goha.ru')
                    site_constr('kanobu.ru')
                    site_constr('kinonews.ru')
                    site_constr('ixbt.com')
                    site_constr('bash.il')
                    site_constr('Habrahabr.ru')
                    sendingmail()
                    log.debug(' Work is over!!\n------------------\n')
                    logsender()
                    time.sleep(x*3600)
                except:
                    log.exception("exception message")
                    logsender()
                    time.sleep(x*3600)
                    main()
            except KeyboardInterrupt:
                main()

if __name__=='__main__':
        main()
        
